package cn.com.inossem.fragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.inossem.activity.AdvancedSearchActivity;
import cn.com.inossem.activity.JobsDetailsActivity;
import cn.com.inossem.activity.ListJobsActivity;
import cn.com.inossem.activity.MainActivity;
import cn.com.inossem.activity.R;
import cn.com.inossem.activity.RetrieveActivity;
import cn.com.inossem.adapter.JobsMessagesAdapter;
import cn.com.inossem.base.RequestFragment;
import cn.com.inossem.config.WSConfig;
import cn.com.inossem.db.DatabaseHelper;
import cn.com.inossem.model.QueryProjectInfoBean;
import cn.com.inossem.model.QueryProjectOpportunityInfoBean;
import cn.com.inossem.model.RetrieveInfoBean;
import cn.com.inossem.pulltorefresh.widget.XListView;
import cn.com.inossem.pulltorefresh.widget.XListView.IXListViewListener;
import cn.com.inossem.requestmanager.WooRequestFactory;
import cn.com.inossem.utils.DemoCache;
import cn.com.inossem.utils.ListSerializable;
import cn.com.inossem.utils.Utils;

import com.foxykeep.datadroid.requestmanager.Request;
import com.netease.nimlib.sdk.auth.LoginInfo;

public class JobsOpportunityFragment extends RequestFragment implements
		IXListViewListener, OnClickListener {
	public static JobsOpportunityFragment mf = null;
	private XListView mMessagesList;
	private JobsMessagesAdapter adapter = null;
	private boolean isRefresh = false;
	public static List<QueryProjectInfoBean> messageInfo = new ArrayList<QueryProjectInfoBean>();
	QueryProjectOpportunityInfoBean bean;// 当前条件

	public static RetrieveInfoBean rib = null;
	ListSerializable ls;

	TextView resulttext;

	RelativeLayout menu, rlbut;
	LinearLayout llayout01, llayout02, llayout03, llayout05;

	public static QueryProjectInfoBean qpib;

	private Handler mHandler = new Handler(new Handler.Callback() {

		@Override
		public boolean handleMessage(Message msg) {
			adapter.notifyDataSetChanged();
			mMessagesList.stopRefresh();
			mMessagesList.stopLoadMore();
			mMessagesList.setRefreshTime(getTime());
			return false;
		}
	});

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		// if (this.isVisible()) {
		// we check that the fragment is becoming visible
		if (isVisibleToUser) {
			mHasLoadedOnce = true;
		} else {
			mHasLoadedOnce = false;
		}
		super.setUserVisibleHint(isVisibleToUser);
	}

	@Override
	public void initAllMembers(Bundle savedInstanceState) {
		super.initAllMembers(savedInstanceState);
		System.out.println("第一页" + mHasLoadedOnce);
		mf = this;
		messageInfo.clear();
		initView();
	}

	public void initView() {

		menu = (RelativeLayout) mRootView.findViewById(R.id.menu);
		rlbut = (RelativeLayout) mRootView.findViewById(R.id.rlbut);
		rlbut.setOnClickListener(this);
		llayout01 = (LinearLayout) mRootView.findViewById(R.id.llayout01);
		llayout01.setOnClickListener(this);
		llayout02 = (LinearLayout) mRootView.findViewById(R.id.llayout02);
		llayout02.setOnClickListener(this);
		llayout03 = (LinearLayout) mRootView.findViewById(R.id.llayout03);
		llayout03.setOnClickListener(this);
		llayout05 = (LinearLayout) mRootView.findViewById(R.id.llayout05);
		llayout05.setOnClickListener(this);

		ImageView search = (ImageView) mRootView.findViewById(R.id.search);
		search.setOnClickListener(this);

		ImageView more = (ImageView) mRootView.findViewById(R.id.more);
		more.setOnClickListener(this);

		resulttext = (TextView) mRootView.findViewById(R.id.resulttext);

		mMessagesList = (XListView) mRootView.findViewById(R.id.inspectionList);
		mMessagesList.setPullRefreshEnable(true);
		mMessagesList.setPullLoadEnable(true);
		mMessagesList.setXListViewListener(this);
		mMessagesList.setRefreshTime(getTime());
		if (mHasLoadedOnce)
			loading();
	}

	public void loading() {
		System.out.println("zhanghao:" + getInfo("zhanghao") + "mima:"
				+ getInfo("mima"));
		if (Utils.isDenglu == 0 && !getInfo("zhanghao").equals("")
				&& !getInfo("mima").equals("")) {
			launchRequest(WooRequestFactory.getLoginDataRequest(
					getInfo("zhanghao"), getInfo("mima")));
		} else if (Utils.isDenglu == 0) {
			bean = new QueryProjectOpportunityInfoBean();
			bean.pageNum = 1;
			launchRequest(WooRequestFactory.getJobsOpportunityDataRequest(bean));
		} else {
			bean = new QueryProjectOpportunityInfoBean();
			bean.pageNum = 1;
			if (rib != null) {
				bean.projectCycle = rib.projectCycle;
				bean.station = rib.station;
				bean.model = rib.model;
				bean.projectAddress = rib.projectAddress;
				bean.projectIndustry = rib.projectIndustry;
			}
			launchRequest(WooRequestFactory.getJobsOpportunityDataRequest(bean));
		}
	}

	private String getInfo(String key) {
		SharedPreferences settings = getActivity().getSharedPreferences(
				"shared_file", 0);
		// 第二个参数为如果SharedPreferences中没有保存就赋一个默认值
		String str = settings.getString(key, "");
		return str;
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (Utils.messageInfo != null && Utils.messageInfo.isPreferences == 0
				&& Utils.pianhaoflag == 0) {
			Utils.pianhaoflag = 1;
			Intent intent = new Intent(getActivity(), RetrieveActivity.class);
			startActivityForResult(intent, 0);
		}
	}

	private String getTime() {
		return new SimpleDateFormat("MM-dd HH:mm", Locale.CHINA)
				.format(new Date());
	}

	@Override
	public int getContentViewId() {
		// TODO Auto-generated method stub
		return R.layout.message_list_layout;
	}

	private LoginInfo getLoginInfo() {
		// 从本地读取上次登录成功时保存的用户登录信息
		String account = Utils.messageInfo.userInfo.getId() + "";
		String token = "db9f13b7b21953594524248188554e16";

		if (!TextUtils.isEmpty(account) && !TextUtils.isEmpty(token)) {
			DemoCache.setAccount(account.toLowerCase());

			System.out.println("聊天登录:-------------------");
			return new LoginInfo(account, token);
		} else {
			return null;
		}
	}

	// 处理返回值
	@Override
	public void onRequestSucess(Request request, Bundle bundle) {
		super.onRequestSucess(request, bundle);

		if (bundle.containsKey(WooRequestFactory.BUNDLE_EXTRA_LOGIN)) {

			System.out.println("登录成功回调!");
			Utils.isDenglu = 1;

			bean = new QueryProjectOpportunityInfoBean();
			if (bundle.containsKey(WooRequestFactory.RESPONSE_LOGIN_DATA)) {
				Utils.messageInfo = bundle
						.getParcelable(WooRequestFactory.RESPONSE_LOGIN_DATA);
			}

			if (bundle.containsKey(WooRequestFactory.PREFERENCES_SETING_DATA)) {
				rib = bundle
						.getParcelable(WooRequestFactory.PREFERENCES_SETING_DATA);
				// 插入数据库
				String[] str = rib.projectCycle.split(",");
				// 109周期108行业126模块127岗位//10924性质
				ContentValues contentValues = new ContentValues();
				contentValues.put("isselected", 1);

				ContentValues Values = new ContentValues();
				Values.put("isselected", 0);
				charu("t_dictionary", Values,
						"pid=126 or pid=127 or pid=109 or pid=108");

				charu("t_areas", Values, "");

				for (int i = 0; i < str.length; i++) {
					charu("t_dictionary", contentValues, "id=" + str[i]);
				}
				str = rib.projectIndustry.split(",");
				for (int i = 0; i < str.length; i++) {
					charu("t_dictionary", contentValues, "id=" + str[i]);
				}
				String _projectAddress = rib.projectAddress;
				if ((null != _projectAddress) && !_projectAddress.trim().equals("")) {
					str = _projectAddress.split(",");
					for (int i = 0; i < str.length; i++) {
						charu("t_dictionary", contentValues, "id=" + str[i]);
					}
				}
				str = rib.model.split(",");
				for (int i = 0; i < str.length; i++) {
					charu("t_dictionary", contentValues, "id=" + str[i]);
				}
				str = rib.station.split(",");
				for (int i = 0; i < str.length; i++) {
					charu("t_dictionary", contentValues, "id=" + str[i]);
				}

				charu("t_areas", Values, "");
				if ((null != _projectAddress) && !_projectAddress.trim().equals("")) {
					str = _projectAddress.split(",");
					for (int i = 0; i < str.length; i++) {
						charu("t_areas", contentValues, "area_id=" + str[i]);
					}
				}

				// ContentValues contentValues = new ContentValues();
				// charu("", contentValues, "");

				// 项目机会查询复值
				bean.pageNum = 1;
				bean.projectCycle = rib.projectCycle;
				bean.station = rib.station;
				bean.model = rib.model;
				bean.projectAddress = rib.projectAddress;
				bean.projectIndustry = rib.projectIndustry;
			} else
				bean.pageNum = 1;
			bean.type = 1;

			// getLoginInfo();
			((MainActivity) getActivity()).doLogin();

			launchRequest(WooRequestFactory.getJobsOpportunityDataRequest(bean));

		} else if (bundle
				.containsKey(WooRequestFactory.BUNDLE_JOBSOPPORTUNITY_LIST)) {
			List<QueryProjectInfoBean> retList = bundle
					.getParcelableArrayList(WooRequestFactory.RESPONSE_JOBSOPPORTUNITY_DATA);
			if (retList == null) {
				if (isRefresh) {
					mMessagesList.stopRefresh();
					mMessagesList.stopLoadMore();
					mMessagesList.setRefreshTime(getTime());
					Toast.makeText(getActivity(), "当前是最后一页！", Toast.LENGTH_LONG)
							.show();
					mMessagesList.setPullLoadEnable(false);
				}
				return;
			}
			if (retList.size() > 0) {
				// mInspections.addAll(retList);
				if (retList.size() < 10) {
					mMessagesList.setPullLoadEnable(false);
				} else {
					mMessagesList.setPullLoadEnable(true);
				}
				if (isRefresh) {
					mMessagesList.stopRefresh();
					mMessagesList.stopLoadMore();
					mMessagesList.setRefreshTime(getTime());
				}
				messageInfo.addAll(retList);
				resulttext.setVisibility(View.GONE);
				mMessagesList.setVisibility(View.VISIBLE);
				System.out.println("长度：" + messageInfo.size());
				if (adapter == null) {
					adapter = new JobsMessagesAdapter(getActivity(),
							messageInfo);
					mMessagesList.setAdapter(adapter);
					mMessagesList
							.setOnItemClickListener(new OnItemClickListener() {

								@Override
								public void onItemClick(AdapterView<?> arg0,
										View arg1, int arg2, long arg3) {

									if (Utils.isDenglu == 0) {
										((MainActivity) getActivity())
												.setPageView(3);
									} else {
										Intent intent = new Intent(
												getActivity(),
												JobsDetailsActivity.class);
										intent.putExtra("id",
												messageInfo.get(arg2 - 1).id);
										startActivity(intent);
									}

								}
							});
					adapter.notifyDataSetChanged();

				} else {
					adapter.notifyDataSetChanged();
				}
				if (Utils.messageInfo != null
						&& Utils.messageInfo.isPreferences == 0
						&& Utils.pianhaoflag == 0) {
					Utils.pianhaoflag = 1;
					Intent intent = new Intent(getActivity(),
							RetrieveActivity.class);
					startActivityForResult(intent, 0);
				}
			} else {
				resulttext.setVisibility(View.VISIBLE);
				mMessagesList.setVisibility(View.GONE);
				mMessagesList.setPullLoadEnable(false);
				if (isRefresh) {
					mMessagesList.stopRefresh();
					mMessagesList.stopLoadMore();
					mMessagesList.setRefreshTime(getTime());
				}
			}

			Intent i_getvalue = getActivity().getIntent();
			String action = i_getvalue.getAction();
			if (Intent.ACTION_VIEW.equals(action)) {
				Uri uri = i_getvalue.getData();
				if (uri != null && Utils.shareflag) {
					String id = uri.getQueryParameter("id");
					if (Utils.isDenglu == 1) {
						Intent intent = new Intent(getActivity(),
								JobsDetailsActivity.class);
						intent.putExtra("id", id);
						startActivity(intent);
					} else {
						((MainActivity) getActivity()).setPageView(3);
					}
					Utils.shareflag = false;
				}
			}
		}

	}

	public void charu(String tabname, ContentValues contentValues,
			String whereClause) {
		DatabaseHelper dh = new DatabaseHelper(getActivity());
		SQLiteDatabase db = dh.getWritableDatabase();

		db.update(tabname, contentValues, whereClause, null);

		db.close();
		dh.close();
	}
	
	@Override
	public void onRefresh() {
		// mMessages.clear();
		// launchRequest(WooRequestFactory.getMessageList(
		// Utils.getVillageID(this), ""));// 发出获取公告请求

		isRefresh = true;
		mMessagesList.setPullLoadEnable(true);
		messageInfo.clear();
		bean.pageNum = 1;
		launchRequest(WooRequestFactory.getJobsOpportunityDataRequest(bean));

		// new Thread() {
		// public void run() {
		// mMessages.clear();
		// //generatorData();
		//
		// try {
		// Thread.sleep(5 * 1000);
		// } catch (InterruptedException e) {
		// e.printStackTrace();
		// }
		// mHandler.sendEmptyMessage(0);
		// }
		//
		// }.start();
		// mHandler.postDelayed(new Runnable() {
		//
		// @Override
		// public void run() {
		// mHandler.sendEmptyMessage(0);
		// }
		// }, 2000);
	}

	@Override
	public void onLoadMore() {// 加载
		if (Utils.isDenglu == 0) {
			((MainActivity) getActivity()).setPageView(3);
			return;
		}
		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				isRefresh = true;
				bean.pageNum += 1;
				launchRequest(WooRequestFactory
						.getJobsOpportunityDataRequest(bean));
			}

		}, 1000);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.more:
			if (Utils.isDenglu == 0) {
				((MainActivity) getActivity()).setPageView(3);
			} else {
				// startActivityForResult(new Intent(getActivity(),
				// DialogActivity.class), 0);
				if (rlbut.getVisibility() == View.VISIBLE) {
					rlbut.setVisibility(View.GONE);

				} else {
					rlbut.setVisibility(View.VISIBLE);

				}
			}
			break;
		case R.id.rlbut:
			rlbut.setVisibility(View.GONE);
			break;
		case R.id.llayout01:
			Intent intent = new Intent(getActivity(), RetrieveActivity.class);
			startActivityForResult(intent, 0);
			rlbut.setVisibility(View.GONE);
			break;
		case R.id.llayout02:
			intent = new Intent(getActivity(), ListJobsActivity.class);
			startActivity(intent);
			rlbut.setVisibility(View.GONE);
			break;
		case R.id.llayout03:
			String[] email = { "zhiren@inossem.com" }; // 需要注意，email必须以数组形式传入
			intent = new Intent(Intent.ACTION_SEND);
			intent.setType("message/rfc822"); // 设置邮件格式
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
			intent.putExtra(Intent.EXTRA_EMAIL, email); // 接收人
			intent.putExtra(Intent.EXTRA_SUBJECT, "来自用户【" + Utils.messageInfo.userInfo.getTruename() + "】的项目需求"); // 主题
			intent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml("<ul><br/><li>客户名称：</li><br/><li>项目名称：</li><br/><li>项目简述：</li><br/><li>开始日期：</li><br/><li>项目周期：</li><br/><li>项目地点：</li><br/><li>付款方式：错月付款/背靠背付款</li><br/><li>薪资模式：大包/包差旅/包住宿</li><br/><li>实施方式：现场/远程</li><br/><li>行业：</li><br/><li>项目性质：管理咨询/规划项目/系统实施/系统运维/售前支持/其他</li><br/><li>专业技能需求：（如：模块要求）</li><br/><li>职位：实习/组员/组长/经理/售前/工程师</li><br/><li>职位要求：（几年相关经验）</li><br/><li>岗位职责：规划/实施/BPR/运维/售前/培训/项目管理</li><br/><li>需求来源：甲方（名称）/咨询商（名称）/猎头（名称）</li><br/><li>联系人：【" + Utils.messageInfo.userInfo.getTruename() + "】</li><br/><li>联系邮箱：【" + Utils.messageInfo.userInfo.getEmail() + "】</li><br/><li>联系电话：【" + Utils.messageInfo.userInfo.getUsername() + "】</li><br/><li>备注：</li></ul><br/><br/>发送即代表同意智仁服务条款，详情请见：http://www.inossem.com/agreement.html")); // 正文
			startActivityForResult(Intent.createChooser(intent, "请选择邮件类应用"), 1001);
			break;
		case R.id.llayout05:
			messageInfo.clear();
			if (adapter != null)
				adapter.notifyDataSetChanged();
			bean = new QueryProjectOpportunityInfoBean();
			bean.projectCycle = "";
			bean.projectIndustry = "";
			bean.model = "";
			bean.station = "";
			bean.projectNature = "";
			bean.projectAddress = "";
			bean.pageNum = 1;
			launchRequest(WooRequestFactory.getJobsOpportunityDataRequest(bean));
			rlbut.setVisibility(View.GONE);
			break;
		case R.id.search:
			if (Utils.isDenglu == 0) {
				((MainActivity) getActivity()).setPageView(3);
			} else {
				startActivityForResult(new Intent(getActivity(),
						AdvancedSearchActivity.class), 0);
			}
			break;
		default:
			break;
		}
	}

	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		switch (resultCode) { // resultCode为回传的标记，我在B中回传的是RESULT_OK
		case 1:
			System.out.println("高级搜索！！！");
			messageInfo.clear();
			if (adapter != null)
				adapter.notifyDataSetChanged();
			bean = new QueryProjectOpportunityInfoBean();
			bean.projectCycle = intent.getStringExtra("projectCycle");
			bean.projectIndustry = intent.getStringExtra("projectIndustry");
			bean.model = intent.getStringExtra("model");
			bean.station = intent.getStringExtra("station");
			bean.projectNature = intent.getStringExtra("projectNature");
			bean.projectAddress = intent.getStringExtra("projectAddress");
			bean.pageNum = 1;
			launchRequest(WooRequestFactory.getJobsOpportunityDataRequest(bean));

			break;
		case 10:
			intent = new Intent(getActivity(), RetrieveActivity.class);
			startActivityForResult(intent, 0);
			break;

		case 99:
			messageInfo.clear();
			if (adapter != null)
				adapter.notifyDataSetChanged();
			launchRequest(WooRequestFactory.getLoginDataRequest(
					getInfo("zhanghao"), getInfo("mima")));
			break;
		default:
			break;
		}
	}

	private void getData(final String id) {
		final HttpGet httpGet = new HttpGet(WSConfig.LOCALURL
				+ "/api/chats/saved/num/" + id);
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					final HttpResponse httpResponse = new DefaultHttpClient()
							.execute(httpGet);
					String result = "";
					if (httpResponse.getStatusLine().getStatusCode() == 200) {
						HttpEntity entity = httpResponse.getEntity();
						try {
							result = EntityUtils.toString(entity);
						} catch (Exception e) {
							e.printStackTrace();
						}
						result.replaceAll("\r", "");
					}
					Message msg = new Message();
					msg.obj = result;
					if (result != null && !result.isEmpty()) {
						if (id != null && !id.isEmpty()) {
							// handler_loadMoreData.sendMessage(msg);
							JSONObject jsonObject = new JSONObject(result);
							Utils.liaotiannum = jsonObject.getInt("count");
						} else {
							// handler_loadData.sendMessage(msg);
						}
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
	}
}
